package com.srwl.mytx.adapter;

import android.content.Context;
import android.graphics.Rect;
import android.graphics.RectF;
import android.media.MediaPlayer;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;

import com.bm.library.Info;
import com.bm.library.PhotoView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.github.florent37.viewanimator.ViewAnimator;
import com.srwl.mytx.Constant;
import com.srwl.mytx.MyApplication;
import com.srwl.mytx.R;
import com.srwl.mytx.domain.AliOssService;
import com.srwl.mytx.domain.MyFile;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.widget.MyVideoPlayer;

import java.util.List;


public class BigPictureAdapter extends PagerAdapter {
    private static final String TAG = "BigPictureAdapter";
    private final Context context;
    private final int screenHeight;
    private final int screenWidth;
    private List<MyFile> myFileList;
    private InteractionListener listener;
    private Info info;//小图位置信息
    private boolean isFirstShow = true;
    private int animationPosition;//当前需要动画的item 选项，不能仅仅依靠 isFirstShow 来判断当前需要动画的 item ，
    private View currentView;
    private SurfaceHolder mSurfaceHolder;
    private MediaPlayer mMediaPlayer;

    public BigPictureAdapter(Context context, List<MyFile> myFileList, InteractionListener listener) {
        this.context = context;
        this.myFileList = myFileList;
        this.listener = listener;
        screenHeight = context.getResources().getDisplayMetrics().heightPixels;
        screenWidth = context.getResources().getDisplayMetrics().widthPixels;
    }

    @Override
    public int getCount() {

        return myFileList.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    //不考这这个方法，notifyDateSetChange()无效
    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull final ViewGroup container, final int position) {
        final View view;
        MyFile myFile = myFileList.get(position);
        if (Constant.MY_FILE_TYPE_PICTURE == myFile.getType()) {
            view = LayoutInflater.from(context).inflate(R.layout.tx_item_big_picture, null);
            final PhotoView photoView = view.findViewById(R.id.iv_picture);
            photoView.enable();
            photoView.setAnimaDuring(400);
            if (isFirstShow && animationPosition == position) {
                photoView.setVisibility(View.INVISIBLE);
            }
            RequestOptions options = new RequestOptions().diskCacheStrategy(DiskCacheStrategy.ALL);
            //判断展示的文件是否为本地文件还是远程文件
            if (myFile.getStatus() == MyFile.FILE_STATUS_LOCAL) {
                //Glide.with(context).asBitmap().load(myFile.getUri()).apply(options).into(photoView);
                GlideLoadUtils.glideLoad(context,myFile.getUri(),photoView);
            } else {
                String loadUrl = AliOssService.TOPIC_IMAGE_PRE_URL + myFile.getUrl();
               // Glide.with(context).asBitmap().load(loadUrl).apply(options).into(photoView);
                GlideLoadUtils.glideLoad(context,loadUrl,photoView);
            }
            photoView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    listener.onItemClick(position);
                }
            });


            TextView tv_count = view.findViewById(R.id.tv_title);
            tv_count.setText((position + 1) + "/" + getCount());
        } else {

            MyVideoPlayer videoPlayer = new MyVideoPlayer(context);
            if (isFirstShow && position == animationPosition) {
                videoPlayer.setVisibility(View.INVISIBLE);
            }
            videoPlayer.ivBack.setOnClickListener(v -> listener.onItemClick(position));

            String videoUrl = myFile.getUrl();
            String proxyUrl;
            if (myFile.getStatus() != MyFile.FILE_STATUS_LOCAL && videoUrl != null && !videoUrl.startsWith("http")) {
                videoUrl = AliOssService.TOPIC_VIDEO_PRE_URL + videoUrl;
                proxyUrl = MyApplication.getProxy(context).getProxyUrl(videoUrl);//视频缓存代理
            } else {
                proxyUrl = videoUrl;//本地视频文件不需要设置代理
            }

            String coverUrl = myFile.getVideoCover();
            if (TextUtils.isEmpty(coverUrl)) {
                coverUrl = videoUrl;
            }
            videoPlayer.init(proxyUrl, coverUrl);
            videoPlayer.tvTitle.setText((position + 1) + "/" + getCount());
            view = videoPlayer;
        }


//        ImageView img_delete = view.findViewById(R.id.img_delete_picture);
//        img_delete.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                destroyItem(container, position, view);
//                listener.onItemRemove(position);
//            }
//        });
        container.addView(view);
        return view;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);

    }

    @Override
    public void setPrimaryItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        super.setPrimaryItem(container, position, object);
        if (currentView != object && currentView != null && currentView instanceof MyVideoPlayer) {
            MyVideoPlayer videoPlayer = (MyVideoPlayer) currentView;
            videoPlayer.pauseVideo();
        }

        currentView = (View) object;//获取当前显示的View,这样才能在按下返回键的时候，拿到photoView,显示缩小的动画
//        Object tag = currentView.getTag();
//        if (Constant.MY_FILE_TYPE_PICTURE == (int) tag) {
//            JzvdStd.resetAllVideos();
//        }
    }


    public void setAnimationPosition(int animationPosition, Info info) {
        this.animationPosition = animationPosition;
        this.info = info;
    }

    public void showAnimateIn(Info info) {
        if (currentView == null) {
            return;
        }
        if (currentView instanceof MyVideoPlayer) {

            currentView.setVisibility(View.VISIBLE);
            MyVideoPlayer videoPlayer = (MyVideoPlayer) currentView;
            videoPlayer.animateEnter(info);
//            RectF smallRect = info.getmImgRect();
//            Rect outRect = new Rect();
//            videoPlayer.ivCover.getHitRect(outRect);
//            float scaleX = smallRect.width() / outRect.width();
//            float scaleY = smallRect.height() / outRect.height();
//            float translationY = outRect.centerY() - info.getmRect().centerY();
//            float translationX = outRect.centerX() - info.getmRect().centerX();
//            ViewAnimator.animate(videoPlayer.ivPlay).scale(0.7f, 1).translationY(translationY, 0).translationX(translationX, 0).duration(400).start();
//            ViewAnimator.animate(videoPlayer.container).scaleX(scaleX, 1).scaleY(scaleY, 1).translationY(translationY, 0).translationX(translationX, 0).duration(400).start();
        } else {
            final PhotoView photoView = currentView.findViewById(R.id.iv_picture);
            View rl_title = currentView.findViewById(R.id.container);
            RectF smallRect = info.getmBaseRect();
            Rect outRect = new Rect();
            photoView.getHitRect(outRect);
            float scaleX = smallRect.width() / outRect.width();
            float scaleY = smallRect.height() / outRect.height();
            float translationY = outRect.centerY() - info.getmRect().centerY();
            float translationX = outRect.centerX() - info.getmRect().centerX();
            ViewAnimator.animate(rl_title).scaleX(scaleX, 1).scaleY(scaleY, 1).alpha(0, 1).translationY(-translationY, 0).translationX(-translationX, 0).duration(400).start();
            // ViewAnimator.animate(rl_title).alpha(0, 1).duration(800).start();
            photoView.setVisibility(View.VISIBLE);
            photoView.animaFrom(info);
        }
        isFirstShow = false;
    }


    public void showAnimateOut(Info smallImageViewInfo) {
        Info bigImageViewInfo;
        if (currentView instanceof MyVideoPlayer) {

            MyVideoPlayer videoPlayer = (MyVideoPlayer) currentView;
            videoPlayer.stopVideo();
            videoPlayer.animateExit(smallImageViewInfo);
        } else {
            PhotoView photoView = currentView.findViewById(R.id.iv_picture);
            View rl_title = currentView.findViewById(R.id.container);
            bigImageViewInfo = PhotoView.getBigImageViewInfo(photoView);
            if (bigImageViewInfo == null) {
                return;
            }
            RectF bigImageRectF = bigImageViewInfo.getmImgRect();
            RectF smallRectF = smallImageViewInfo.getmImgRect();
            float scaleX = smallRectF.width() / bigImageRectF.width();
            float scaleY = smallRectF.height() / bigImageRectF.height();
            float translationY = bigImageViewInfo.getmRect().centerY() - smallImageViewInfo.getmRect().centerY();
            float translationX = bigImageViewInfo.getmRect().centerX() - smallImageViewInfo.getmRect().centerX();
            ViewAnimator.animate(rl_title)
                    .scaleX(scaleX).scaleY(scaleY).alpha(1, 0)
                    .translationY(0, -translationY).translationX(0, -translationX)
                    .duration(200)//动画执行时间 ，不能设置为400，不然会看起滞后于photoView的动画
                    .start();
            photoView.animaTo(smallImageViewInfo, new Runnable() {
                @Override
                public void run() {
                    //  reset();
                }
            });
            //ViewAnimator.animate(currentView).scaleX(scaleX).scaleY(scaleY).translationY(0, -translationY).translationX(0, -translationX).duration(400).start();

        }
        isFirstShow = true;
    }


    public interface InteractionListener {

        void onItemClick(int position);

        void onItemRemove(int position);
    }
}
